package com.hetwen.demo.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.keepalive.KeepAliveFilter;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaServer {

    private static final int KEEP_ALIVE_INTERVAL = 15;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		NioSocketAcceptor acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory()));
		//心跳保活
		KeepAliveFilter heartBeat = new KeepAliveFilter(new KeepAliveMessageFactoryImpl(), IdleStatus.BOTH_IDLE);
		heartBeat.setForwardEvent(true);
		heartBeat.setRequestInterval(KEEP_ALIVE_INTERVAL);
		acceptor.getFilterChain().addLast("heartbeat", heartBeat);
		acceptor.setHandler(new ServerHandler());
		try {
			acceptor.bind(new InetSocketAddress("192.168.40.65",8001));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    private static class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {

        @Override
        public boolean isRequest(IoSession ioSession, Object o) {
            if ("1".equals(o)) {
                return true;
            }
            return false;
        }

        @Override
        public boolean isResponse(IoSession ioSession, Object o) {
            return false;
        }

        @Override
        public Object getRequest(IoSession ioSession) {
            return null;
        }

        @Override
        public Object getResponse(IoSession ioSession, Object o) {
            return "2";
        }
    }

}
